<template>
  <el-dialog
    :title="props.operType === 'add' ? '新增设备广告' : '编辑设备广告'"
    v-model="visible"
    width="50%"
    append-to-body
  >
    <el-form :model="form" :rules="rules" ref="advertDeviceRef" label-width="100px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="设备机器" prop="machineId">
            <div class="select-box">
              <el-input
                v-model="form.machineId"
                placeholder="请选择设备"
                maxlength="60"
                clas="input-box"
              />
              <el-button @click="handleAddFileColumn" type="primary">选择设备</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8"> </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="广告名称" prop="adId">
            <el-select
              v-model="form.adId"
              style="width: 100%"
              placeholder="请选择广告"
              @change="getAdvertContentById(form.adId)"
            >
              <el-option
                v-for="(item, index) in adverOptions"
                :key="index"
                :label="item.name"
                :value="item.adId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8"> </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="广告类型" prop="adType">
            <el-select v-model="form.adType" disabled placeholder="请选择广告" style="width: 100%">
              <el-option
                v-for="dictType in device_ad_type"
                :key="dictType.value"
                :label="dictType.label"
                :value="dictType.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
      <el-row v-if="form.adType">
        <el-col :span="16">
          <el-form-item label="广告内容" prop="">
            <div v-if="form.adType == 1">
              <el-image
                :src="form.resourceUrl"
                fit="fill"
                class="form-img"
                @click="handlePictureCardPreview(form.resourceUrl)"
              />
            </div>
            <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
              <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
            </el-dialog>
            <div v-if="form.adType == 2">
              <video
                :src="form.resourceUrl"
                width="200"
                preload
                :autoplay="false"
                controls
                class="video-box"
              ></video>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="广告位置" prop="palyAdPosition">
            <el-select
              v-model="form.palyAdPosition"
              placeholder="请选择广告位置"
              style="width: 100%"
            >
              <el-option
                v-for="dict in device_ad_position"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8"> </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="开始时间" prop="palyBeginTime">
            <el-date-picker
              v-model="form.palyBeginTime"
              type="datetime"
              placeholder="请选择时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8"> </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="结束时间" prop="playEndTime">
            <el-date-picker
              v-model="form.playEndTime"
              type="datetime"
              placeholder="请选择时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8"> </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loadingSubmit">{{
          props.operType === 'add' ? '新增' : '更新'
        }}</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    title="选择设备"
    @close="closeMachineDialog"
    v-model="visibleMachine"
    width="60%"
    append-to-body
  >
    <el-row :gutter="20">
      <!--点位数据-->
      <el-col :span="6" :xs="24">
        <div class="position-box">
          <el-radio-group v-model="positionTypeId" @change="getPositionType(positionTypeId)">
            <div class="title2">· 普通点位</div>
            <el-radio
              style="margin: 0 0 0 20px"
              v-for="(item, index) in positionTypeOptions"
              :key="index"
              :label="item.positionTypeId"
              :value="item.positionTypeId"
              >{{ item.typeName }}</el-radio
            >
            <div class="title3">· 特殊点位</div>
            <el-radio
              style="margin: 0 0 0 20px"
              v-for="(item, index) in specialPositionTypeOptions"
              :key="index"
              :label="item.positionTypeId"
              :value="item.positionTypeId"
              >{{ item.typeName }}</el-radio
            >
          </el-radio-group>
        </div>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="设备标签" prop="machineTag">
            <el-select
              v-model="queryParams.machineTag"
              @change="getList('search')"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in tagOptions"
                :key="item.tagId"
                :label="item.tagName"
                :value="item.tagId"
                size="small"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型" prop="machineType">
            <el-select
              v-model="queryParams.machineType"
              @change="getList('search')"
              placeholder="请选择"
              filterable
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="城市标签" prop="cityName">
            <el-select
              v-model="queryParams.cityName"
              fit-input-width
              clearable
              placeholder="请选择"
              @change="getList('search', 'tag')"
            >
              <el-option
                v-for="item in cityNameOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleSearchResect" size="small">重置</el-button>
            <el-button type="primary" @click="getList('search', 'tag')" size="small"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="tableListAll"
          max-height="580"
          @selection-change="handleSelectionChange"
          ref="tableAllRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="设备编号"
            align="center"
            prop="machineId"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="设备名称"
            align="center"
            prop="machineName"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="设备标签"
            align="center"
            prop="machineTag"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="投放地点"
            align="center"
            prop="positionAddr"
            :show-overflow-tooltip="true"
            min-width="90"
          />
        </el-table>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeMachineDialog">取 消</el-button>
        <el-button type="primary" @click="confirmSelected">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { defineProps, reactive, watch, onMounted, nextTick } from 'vue'
import {
  getAdvertList,
  getMachineList,
  addMachineAdvert,
  getMachineAdvertDetail,
  updateMachineAdvert
} from '@/api/advert'
import { getDeviceTagList } from '@/api/device/tag'
import { getPointTypeList } from '@/api/organization/pointType'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

const props = defineProps({
  operType: {
    type: String,
    default: 'add'
  }
})
const emit = defineEmits(['updateList'])
const { proxy } = getCurrentInstance()
const { device_ad_type, device_ad_position, device_type } = proxy.useDict(
  'device_ad_type',
  'device_ad_position',
  'device_type'
)
const visible = ref(false)
const loadingSubmit = ref(false)
const advertDeviceRef = ref()

const form = ref({
  machineAdId: null,
  machineId: null,
  adId: null,
  adType: null,
  palyBeginTime: null,
  playEndTime: null,
  palyAdPosition: null
})
const rules = {
  machineId: [{ required: true, message: '设备机器不能为空', trigger: ['blur', 'change'] }],
  adId: [{ required: true, message: '广告不能为空', trigger: ['blur', 'change'] }],
  adType: [{ required: true, message: '广告类型不能为空', trigger: ['blur', 'change'] }],
  palyAdPosition: [
    { required: true, message: '广告播放位置不能为空', trigger: ['blur', 'change'] }
  ],
  palyBeginTime: [{ required: true, message: '开始时间不能为空', trigger: ['blur', 'change'] }],
  playEndTime: [{ required: true, message: '结束时间不能为空', trigger: ['blur', 'change'] }]
}

//** 设备标签 && 点位类型 && 广告列表 */
const tagOptions = ref([])
const positionTypeId = ref(null)
const positionTypeOptions = ref([]) // 普通点位
const specialPositionTypeOptions = ref([]) // 特殊点位
const adverOptions = ref([])
function getOptions() {
  getDeviceTagList({ pageNum: 1, pageSize: 1000, cityName: queryParams.value.cityName }).then(
    (res) => {
      tagOptions.value = res.rows
    }
  )
  getPointTypeList({ pageNum: 1, pageSize: 1000, cityName: queryParams.value.cityName }).then(
    (r) => {
      positionTypeOptions.value = r?.rows?.filter((i) => i?.type === 2)
      specialPositionTypeOptions.value = r?.rows?.filter((i) => i?.type === 1)
    }
  )
  getAdvertList({ pageNum: 1, pageSize: 1000 }).then((e) => {
    adverOptions.value = e.rows
  })
}
function getAdvertContentById(adId) {
  const selectedType = adverOptions.value.find((option) => option.adId == adId)
  form.value.resourceUrl = selectedType ? selectedType.resourceUrl : null
  form.value.adType = selectedType ? selectedType.type.toString() : null
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
function handlePictureCardPreview(url) {
  dialogImageUrl.value = url
  dialogVisible.value = true
}

//** 设备列表 */
const queryParams = ref({
  machineTag: null,
  positionTypeId: null,
  machineType: '',
  cityName: ''
})
const tableListAll = ref([])
const tableList = ref([])
function getList(search, tag) {
  let selectedIds = selected.value.map((item) => item.machineId)
  if (tag) {
    queryParams.value.machineTag = null
    getDeviceTagList({ pageNum: 1, pageSize: 1000, cityName: queryParams.value.cityName }).then(
      (res) => {
        tagOptions.value = res.rows || []
        console.log('first', tagOptions.value)
      }
    )
    getPointTypeList({ pageNum: 1, pageSize: 1000, cityName: queryParams.value.cityName }).then(
      (r) => {
        positionTypeOptions.value = r?.rows?.filter((i) => i?.type === 2)
        specialPositionTypeOptions.value = r?.rows?.filter((i) => i?.type === 1)
      }
    )
  }
  getMachineList(queryParams.value).then((res) => {
    tableListAll.value = res.data
    if (search === 'search') {
      setTimeout(() => {
        tableListAll.value.forEach((ele) => {
          if (selectedIds.includes(ele.machineId)) {
            tableAllRef.value.toggleRowSelection(ele, true)
          }
        })
      }, 100)
    }
  })
}
function handleSearchResect() {
  queryParams.value.machineTag = null
  positionTypeId.value = null
  queryParams.value.positionTypeId = null
  queryParams.value.machineType = ''
  getList('search')
}
function getPositionType(positionTypeId) {
  queryParams.value.positionTypeId = positionTypeId
  getList('search')
}

//** 选择设备 */
const visibleMachine = ref(false)
const tableAllRef = ref(null)
const cityName = ref(null)
function handleAddFileColumn() {
  getList()
  visibleMachine.value = true
  console.log('queryParams.value.cityName', queryParams.value.cityName)
  let selectedIds = tableList.value.map((item) => item.machineId)
  tableListAll.value.forEach((row) => {
    if (selectedIds.includes(row.machineId)) {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, true)
      })
    } else {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, false)
      })
    }
  })
}
const selected = ref([])
const handleSelectionChange = (val) => {
  selected.value = val
}
const confirmSelected = () => {
  tableList.value = selected.value
  visibleMachine.value = false
  let arr = tableList.value.map((ele) => ele.machineName)
  form.value.machineId = arr.join(',')
}
const closeMachineDialog = () => {
  selected.value = []
  visibleMachine.value = false
  queryParams.value = {
    machineTag: null,
    positionTypeId: null,
    machineType: ''
  }
}

//** form提交 */
function submitForm() {
  proxy.$refs['advertDeviceRef'].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true
      let params = {
        ...form.value,
        machineId: tableList.value.map((ele) => ele.machineId).join(',')
      }
      delete params.resourceUrl
      if (props.operType === 'add') {
        addMachineAdvert(params).then(
          (res) => {
            proxy.$modal.msgSuccess('新增成功')
            emit('updateList')
            visible.value = false
          },
          (error) => {
            loadingSubmit.value = false
          }
        )
      } else {
        ElMessageBox.confirm('确认要修改这行数据吗?', '系统提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        })
          .then(() => {
            updateMachineAdvert({ ...params, machineAdId: currentId.value }).then((res) => {
              proxy.$modal.msgSuccess('更新成功')
              emit('updateList')
              visible.value = false
            })
          })
          .catch(() => {
            loadingSubmit.value = false
          })
      }
    }
  })
}
//** init */
const currentId = ref()
function show(cityName, type, id) {
  queryParams.value.cityName = cityName
  getOptions()
  reset()
  visible.value = true
  if (type === 'edit') {
    getDetailData(id)
    currentId.value = id
  }
}
//** 详情 */
function getDetailData(id) {
  getMachineAdvertDetail(id).then((res) => {
    let data = res?.data || null
    form.value = {
      machineAdId: data.machineAdId ? data.machineAdId : null,
      adId: data.adId ? data.adId : null,
      adType: data.adType ? data.adType.toString() : null,
      resourceUrl: data.adUrl ? data.adUrl : null,
      palyBeginTime: data.palyBeginTime ? data.palyBeginTime : null,
      playEndTime: data.playEndTime ? data.playEndTime : null,
      palyAdPosition: data.palyAdPosition ? data.palyAdPosition.toString() : null
    }
    //设备回显
    let obj = {
      machineId: data.machineId ? data.machineId : null,
      machineSn: data.machineSn ? data.machineSn : null,
      machineName: data.machineName ? data.machineName : null
    }
    tableList.value = [obj]
    let arr = tableList.value.map((ele) => ele.machineName)
    form.value.machineId = arr.join(',')
  })
}
//** form重置 */
function reset() {
  form.value = {
    machineAdId: null,
    machineId: null,
    adId: null,
    adType: null,
    palyBeginTime: null,
    playEndTime: null,
    palyAdPosition: null
  }
  tableList.value = []
  if (advertDeviceRef.value) {
    advertDeviceRef.value.resetFields()
  }
  loadingSubmit.value = false
}
defineExpose({
  show
})
</script>

<style lang="scss" scoped>
.select-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .input-box {
    width: 80%;
  }
}
:deep(.el-radio) {
  width: 100%;
}
.position-box {
  background-color: #f2f2f2;
  width: 100%;
  min-height: 300px;
  max-height: 600px;
  padding: 8px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.form-img {
  height: 100px;
  margin-left: 8px;
  border-radius: 8px;
  cursor: pointer;
}
.title2 {
  width: 100%;
  margin-bottom: 5px;
  font-size: 14px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    Arial, sans-serif;
}
.title3 {
  width: 100%;
  margin: 20px 0 5px 0;
  font-size: 14px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    Arial, sans-serif;
}
</style>
